<template>
  <el-row :gutter="20">
    <el-col :span="4">
      <el-tree :props="props" :load="loadNode" @node-click="handleNodeClick" highlight-current="true"
        expand-on-click-node="false" lazy>
      </el-tree>

      <el-upload drag :action="uploadFile()" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
        :on-success="handleUploadSuccess" :on-error="handleUploadError" list-type="picture">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>

      <div>
        <el-dialog :visible.sync="dialogVisible">
          <img :src="dialogImageUrl" />
        </el-dialog>
      </div>

      <div style="padding:10px"></div>
      <div id="preview" v-on:paste="handlePaste">
        <span>按Ctrl+V粘贴</span>
      </div>
      <el-button v-on:click="uploadPlans">上传文件</el-button>

    </el-col>

    <el-col :span="20">
      <div class="container">

        <div>
          <MyWaterfall :data="imgList"></MyWaterfall>
        </div>

      </div>
    </el-col>

  </el-row>

</template>

<script>
import axios from 'axios'
import MyWaterfall from './MyWaterfall.vue'
import http from '@/utils/upload'

export default {
  components: { MyWaterfall },
  data() {
    return {
      props: {
        label: 'name',
        children: 'zones',
        isLeaf: 'leaf',
      },
      dialogImageUrl: '',
      dialogVisible: false,
      parPath: '0',
      newfileName: '',
      images: [],
      imgList: [],
      dirName: '',
      currentPath: '',
      directoryList: [],
      newDirName: '',
      file: undefined,
    }
  },
  mounted() {
    //注册黏贴事件
    document.addEventListener('paste', this.handlePaste)
  },
  created() {
    this.getPicture(this.parPath)
  },
  methods: {
    getDirectory() {
      var that = this
      axios({
        method: 'get',
        url: 'https://localhost:44313/Album/GetDirector?path=' + that.parPath,
      }).then(
        (res) => {
          clog('getDirectory', res.data)
          that.directoryList = res.data
          console.log(res)
        },
        (res) => {
          this.$message.error('wrong')
        }
      )
    },
    loadNode(node, resolve) {
      clog('loadNode', node)
      let that = this
      if (node.level === 0) {
        var tmp = $.ajax({
          url: 'https://localhost:44313/Album/GetDirector?path=0',
          type: 'GET',
          async: false,
          success: function (data) {},
          error: function (error) {
            clog('ajax.error', error)
            that.showMessage('ajax.error:' + error)
          },
        }).responseJSON
        return resolve(tmp)
      }

      var tmp = $.ajax({
        url: 'https://localhost:44313/Album/GetDirector?path=' + node.data.path,
        type: 'GET',
        async: false,
        success: function (data) {},
        error: function (error) {
          clog('ajax.error', error)
          that.showMessage('ajax.error:' + error)
        },
      }).responseJSON
      return resolve(tmp)
    },
    handleNodeClick(data) {
      clog('handleNodeClick', data)
      if (this.currentPath !== data.path) {
        this.currentPath = data.path
        this.getPicture(data.path)
      }
    },
    //黏贴图片
    handlePaste(event) {
      const items = (event.clipboardData || window.clipboardData).items
      let file = null

      if (!items || items.length === 0) {
        this.$message.error('当前浏览器不支持本地')
        return
      }
      // 搜索剪切板items
      for (let i = 0; i < items.length; i++) {
        if (items[i].type.indexOf('image') !== -1) {
          file = items[i].getAsFile()
          break
        }
      }
      if (!file) {
        this.$message.error('粘贴内容非图片')
        return
      }
      // 此时file就是我们的剪切板中的图片对象
      // 如果需要预览，可以执行下面代码
      const reader = new FileReader()
      reader.onload = (event) => {
        preview.innerHTML = `<img src="${event.target.result}">`
      }
      reader.readAsDataURL(file)
      this.file = file
    },
    //黏贴后上传
    uploadPlans() {
      let that = this
      let file = this.file
      if (!file) {
        this.$message.error('请粘贴图片后上传')
        return
      }
      this.loading = true
      let formData = new FormData()
      formData.append('file', file)
      formData.append('type', this.type)
      http
        .uploadFile('Upload?directoryPath=' + this.currentPath + '&fileName=' + this.newfileName, formData)
        .then(function (response) {
          if (response.status === 200) {
            that.showMessage('上传成功!')
            preview.innerHTML = `<span>将图片按Ctrl+V 粘贴至此处</span>`
          } else {
            that.showMessage('上传失败!')
          }
        })
    },

    dialogVisibleConfirm() {
      var that = this
      axios({
        method: 'get',
        url: 'https://localhost:44313/Album/AddDirector?path=' + that.parPath + '\\' + that.newDirName,
      }).then(
        (res) => {
          if (res.data === 500) {
            this.$message.error('该目录下已存在相同名称！')
          }
          if (res.data === 200) {
            this.$message.success('添加成功！')
          }
          if (res.data === -1) {
            this.$message.error('wrong')
          }
        },
        (res) => {
          this.$message.error('wrong')
        }
      )
    },
    getPicture(parPath) {
      var that = this
      this.imgList.length = 0
      axios({
        method: 'get',
        url: 'https://localhost:44313/Album/GetFile?path=' + parPath,
      }).then(
        (res) => {
          for (var i = 0; i < res.data.length; i++) {
            this.imgList.push({
              imgSrc: 'https://localhost:44313/Album/GetAllImage?imgPath=' + res.data[i].imgSrc.replace(/\\/g, '/'), //网页加载图片路径
              fullSrc: res.data[i].imgSrc, //原路径
              title: res.data[i].title, //无后缀名称
              fullTitle: res.data[i].fullTitle,
            })
          }
        },
        (res) => {
          that.$message.error('加载失败')
          that.noMore = true
        }
      )
    },
    uploadFile() {
      var that = this
      return 'https://localhost:44313/Album/Upload?directoryPath=' + that.directoryPath + '&fileName=' + that.parPath
    },
    handleRemove(file, fileList) {
      this.images.forEach((element, index, arr) => {
        if (file.name === element.oldFile.name) {
          arr.splice(index, 1)
        }
      })
      console.log(this.images)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleUploadSuccess(res, file, fileList) {
      var that = this
      fileList.name = that.newfileName
      file.name = that.newfileName
      this.getPicture() //重新渲染瀑布流
      this.images.push({
        newFileName: res.newFileName,
        oldFile: {
          name: file.name,
          url: file.url,
        },
      })
    },
    handleUploadError(res, file, fileList) {
      this.$message.error(res.message)
    },
    showMessage(message) {
      this.$message.success(message)
    },
  },
}
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
}
.directoryTitle {
  margin-bottom: 6px;
}
.directoryTitle:hover {
  color: rgb(92, 192, 196);
}
</style>
